package com.binyouwei.udp_lib.factory;

import android.util.Log;

import androidx.annotation.NonNull;

import com.binyouwei.udp_lib.ReceiveMessageInterface;
import com.binyouwei.udp_lib.SingleThreads;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author 宾有为
 * @date 2024/6/13 14:39
 * @link https://blog.csdn.net/baidu_41616022?type=blog
 * @describe：直接广播
 **/
public class DirectBroadcastFactory implements UdpFactory {
    final String TAG = getClass().getSimpleName();
    boolean isFinish = false;
    private static final int PORT = 6666;

    @Override
    public void initUdp() {
        isFinish = true;
    }

    @Override
    public void destroyUdp() {
        isFinish = false;
    }

    @Override
    public void sendMessage(@NonNull String ip, @NonNull String message) {
        SingleThreads.getInstance().execute(() -> {
            try {
                // 创建DatagramSocket实例，并启用广播
                DatagramSocket socket = new DatagramSocket();
                socket.setBroadcast(true);
                // 准备发送的数据
                byte[] sendData = message.getBytes();
                // 构建DatagramPacket，目标地址为子网广播地址，IP 一般为 192.168.子网网段.255
                InetAddress broadcastAddress = InetAddress.getByName(ip);
                DatagramPacket packet = new DatagramPacket(sendData, sendData.length, broadcastAddress, PORT);
                // 发送广播数据包
                socket.send(packet);
                Log.e(TAG, "发送广播成功，message：" + message);
                // 关闭socket
                socket.close();
            } catch (IOException e) {
                Log.e(TAG, "发送广播失败，message：" + e.getMessage());
                e.printStackTrace();
            }
        });
    }

    @Override
    public void onReceiveMessageListener(@NonNull String ip, @NonNull ReceiveMessageInterface receiveMessage) {
        SingleThreads.getInstance().execute(() -> {
            try {
                // 创建缓冲区以接收数据
                byte[] receiveData = new byte[1024];
                DatagramSocket socket = new DatagramSocket(PORT);
                socket.setBroadcast(true);
                while (isFinish) {
                    // 创建DatagramPacket来接收数据
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                    // 接收广播消息
                    socket.receive(receivePacket);
                    // 处理接收到的数据
                    String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
                    receiveMessage.onReceiveMessageListener(message);
                    Log.e(TAG, "广播收到一条消息，message：" + message);
                }
                socket.close();
            } catch (IOException e) {
                Log.e(TAG, "广播接收消息失败，message：" + e.getMessage());
                throw new RuntimeException(e);
            }
        });
    }
}
